package com.alibaba.gao.utils;

import com.alibaba.gao.pojo.JdContent;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hcgao
 * @version 1.0.0
 * @ClassName HtmlParseUtils.java
 * @Description TODO
 * @createTime 2021年08月30日 21:11:00
 */
@Component
public class HtmlParseUtils {

    public static void main(String[] args) throws IOException {
        new HtmlParseUtils().parseJD("java").forEach(System.out::println);
    }

    public List<JdContent> parseJD(String keywords) throws IOException {
        //获取请求
        String url = "https://search.jd.com/Search?keyword="+keywords;

        //解析网页，返回html的 Document对象
        Document document = Jsoup.parse(new URL(url), 30000);

        Element element = document.getElementById("J_goodsList");

        System.out.println(element.html());
        //获取所有的 Li标签
        Elements elements = element.getElementsByTag("li");

        ArrayList<JdContent> goodsList = new ArrayList<>();

        for (Element el : elements) {
            String image = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            JdContent content = new JdContent();
            content.setTitle(title);
            content.setPrice(price);
            content.setImg(image);
            goodsList.add(content);
        }
        return goodsList;
    }
}
